package com.jingli.pile.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jingli.pile.converter.ConnectorConverter;
import com.jingli.pile.converter.EquipmentConverter;
import com.jingli.pile.converter.OperatorConvertor;
import com.jingli.pile.converter.StationConverter;
import com.jingli.pile.domain.KafkaChargeStatus;
import com.jingli.pile.domain.KafkaPortStatus;
import com.jingli.pile.domain.StationInfoData;
import com.jingli.pile.domain.SupStationStatsPushVo;
import com.jingli.pile.entity.*;
import com.jingli.pile.kafka.KafkaMessageConsumer;
import com.jingli.pile.request.StationQueryRequest;
import com.jingli.pile.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/apiTest")
public class TestApiController {
    private Logger logger = LoggerFactory.getLogger(TestApiController.class);
    @Autowired
    private PlotService plotService;
    @Autowired
    private SupStationInfoService stationInfoService;
    @Autowired
    private StationConverter stationConverter;
    @Autowired
    private XtUserService xtUserService;
    @Autowired
    private SupOperatorInfoService operatorInfoService;
    @Autowired
    private OperatorConvertor operatorConvertor;
    @Autowired
    private ChargingPileService chargingPileService;
    @Autowired
    private ChargingPortService chargingPortService;
    @Autowired
    private EquipmentConverter equipmentConverter;
    @Autowired
    private ConnectorConverter connectorConverter;
    @Autowired
    private SupEquipmentInfoService equipmentInfoService;
    @Autowired
    private SupConnectorInfoService connectorInfoService;
    @Autowired
    private KafkaMessageConsumer kafkaMessageConsumer;
    @Autowired
    private SupStationStatsInfoService supStationStatsInfoService;
    @Autowired
    private SupStationStatusInfoService stationStatusInfoService;
    @Autowired
    private SupConnectorStatusInfoService connectorStatusInfoService;

    @RequestMapping("/station")
    @ResponseBody
    public void getPlot(){
        List<Plot> list = plotService.list();
        for (Plot plot : list) {
            QueryWrapper<SupStationInfo> stationInfoQueryWrapper = new QueryWrapper<>();
            stationInfoQueryWrapper.eq("plot_id",plot.getId());
            SupStationInfo stationInfo = stationInfoService.getOne(stationInfoQueryWrapper);
            if (null!=stationInfo){
                continue;
            }
            SupStationInfo supStationInfo = stationConverter.convertPlotToStationInfo(plot);
            stationInfoService.saveOrUpdate(supStationInfo);
        }
    }

    @RequestMapping("/operator")
    @ResponseBody
    public void operator(){
        QueryWrapper<XtUser> xtUserQueryWrapper = new QueryWrapper<>();
        xtUserQueryWrapper.eq("is_operator","1");
        List<XtUser> list = xtUserService.list(xtUserQueryWrapper);
        for (XtUser user : list) {
            QueryWrapper<SupOperatorInfo> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_id",user.getId());
            SupOperatorInfo operatorInfo = operatorInfoService.getOne(userQueryWrapper);
            if (null!=operatorInfo){
                continue;
            }
            SupOperatorInfo supOperatorInfo = operatorConvertor.convertUserTOOperator(user);
            operatorInfoService.saveOrUpdate(supOperatorInfo);
        }
    }

    @RequestMapping("/equip")
    @ResponseBody
    public void equip(){
        List<ChargingPile> chargingPiles = chargingPileService.list();
        for (ChargingPile pile : chargingPiles) {
            QueryWrapper<SupEquipmentInfo> equipmentInfoQueryWrapper = new QueryWrapper<>();
            equipmentInfoQueryWrapper.eq("equipmentID",pile.getId());
            SupEquipmentInfo equipmentInfo = equipmentInfoService.getOne(equipmentInfoQueryWrapper);
            if (null!=equipmentInfo){
                continue;
            }
            SupEquipmentInfo supEquipmentInfo = equipmentConverter.convertEquipFromPile(pile);
            equipmentInfoService.saveOrUpdate(supEquipmentInfo);
        }
    }

    @RequestMapping("/connector")
    @ResponseBody
    public void connector(){
        List<ChargingPort> chargingPorts = chargingPortService.list();
        for (ChargingPort port : chargingPorts) {
            QueryWrapper<SupConnectorInfo> connectorInfoQueryWrapper = new QueryWrapper<>();
            connectorInfoQueryWrapper.eq("connector_id",port.getId());
            SupConnectorInfo supConnectorInfo = connectorInfoService.getOne(connectorInfoQueryWrapper);
            if (null!=supConnectorInfo){
                continue;
            }
            SupConnectorInfo connectorInfo = connectorConverter.convertConnectorFromPort(port);
            connectorInfoService.saveOrUpdate(connectorInfo);
        }
    }

    @RequestMapping("/stationStatus")
    @ResponseBody
    public void stationStatus(){
        List<SupStationInfo> stationInfos = stationInfoService.list();
        for (SupStationInfo stationInfo : stationInfos) {
            SupStationStatusInfo statusInfo = new SupStationStatusInfo();
            statusInfo.setOperatorId(stationInfo.getOperatorId());
            statusInfo.setEquipmentOwnerId(stationInfo.getOperatorId());
            statusInfo.setStationId(stationInfo.getStationId());
            QueryWrapper<SupStationStatusInfo> supStationStatusInfoQueryWrapper = new QueryWrapper<>();
            supStationStatusInfoQueryWrapper.eq("station_id",stationInfo.getStationId());
            SupStationStatusInfo one = stationStatusInfoService.getOne(supStationStatusInfoQueryWrapper);
            if (null==one){
                stationStatusInfoService.save(statusInfo);
            }
            QueryWrapper<SupEquipmentInfo> equipmentInfoQueryWrapper = new QueryWrapper<>();
            equipmentInfoQueryWrapper.eq("station_id",stationInfo.getStationId());
            List<SupEquipmentInfo> supEquipmentInfos = equipmentInfoService.list(equipmentInfoQueryWrapper);
            if (supEquipmentInfos.isEmpty()){
                continue;
            }
            List<String> ids = new ArrayList<>();
            for (SupEquipmentInfo equipmentInfo :supEquipmentInfos) {
                ids.add(equipmentInfo.getEquipmentid());
            }
            QueryWrapper<SupConnectorInfo> connectorInfoQueryWrapper = new QueryWrapper<>();
            connectorInfoQueryWrapper.in("equipment_id",ids);
            List<SupConnectorInfo> connectorInfos = connectorInfoService.list(connectorInfoQueryWrapper);
            for (SupConnectorInfo connectorInfo : connectorInfos) {
                SupConnectorStatusInfo connectorStatusInfo = new SupConnectorStatusInfo();
                connectorStatusInfo.setConnectorId(connectorInfo.getConnectorId());
                connectorStatusInfo.setOperatorId(stationInfo.getOperatorId());
                connectorStatusInfo.setEquipmentClassification(1);
                connectorStatusInfo.setStationId(stationInfo.getStationId());
                connectorStatusInfo.setEquipmentId(connectorInfo.getEquipmentId());
                connectorStatusInfo.setStatus(1);
                connectorStatusInfo.setEquipmentOwnerId(stationInfo.getOperatorId());
                connectorStatusInfo.setStatusDesc("空闲");
                connectorStatusInfo.setLastChangeTime(LocalDateTimeUtil.format(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss"));
                connectorStatusInfoService.saveOrUpdate(connectorStatusInfo);
            }
        }
    }

    /**
     * 推送充电设备接口状态信息
     * @return
     */
    @RequestMapping("/pushConnectorStatus")
    @ResponseBody
    public String pushConnectorStatus(@RequestBody KafkaPortStatus kafkaPortStatus){
        try {
            kafkaMessageConsumer.pushPortStatus(JSONObject.toJSONString(kafkaPortStatus));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    /**
     * 推送充电状态信息
     * @return
     */
    @RequestMapping("/pushChargeStatus")
    @ResponseBody
    public String pushChargeStatus(@RequestBody KafkaChargeStatus chargeStatus){
        try {
            kafkaMessageConsumer.pushChargeStatus(JSONObject.toJSONString(chargeStatus));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    /**
     * 推送充电状态信息
     * @return
     */
    @RequestMapping("/pushOperateStats")
    @ResponseBody
    public String pushOperateStats(@RequestParam("stationId") String stationId){
        QueryWrapper<SupStationStatsInfo> supStationStatsInfoQueryWrapper = new QueryWrapper<>();
        supStationStatsInfoQueryWrapper.eq("station_id",stationId);
        SupStationStatsInfo supStationStatsInfoServiceOne = supStationStatsInfoService.getOne(supStationStatsInfoQueryWrapper);
        SupStationStatsPushVo supStationStatsPushVo = new SupStationStatsPushVo();
        List<SupStationStatsInfo> stationStatsInfos = new ArrayList<>();
        stationStatsInfos.add(supStationStatsInfoServiceOne);
        supStationStatsPushVo.setStationStatsInfos(stationStatsInfos);
        try {
            kafkaMessageConsumer.pushOperatorStatsInfo(supStationStatsPushVo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    /**
     * 推送充电状态信息
     * @return
     */
    @RequestMapping("/pushChargeOrderInfo")
    @ResponseBody
    public String pushChargeOrderInfo(@RequestParam("ordernumber") String orderNumber){
        try {
            kafkaMessageConsumer.consumeOrder(orderNumber);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    @RequestMapping("/stationInfo")
    @ResponseBody
    public String stationInfo(){
        StationQueryRequest stationQueryRequest = new StationQueryRequest();
        stationQueryRequest.setPageNo(1);
        stationQueryRequest.setPageSize(500);
        Page<SupStationInfo> supStationInfoPage = stationInfoService.queryStationInfo(stationQueryRequest);
        StationInfoData infoData = new StationInfoData();
        infoData.setStationInfos(supStationInfoPage.getRecords());
        infoData.setItemSize((int) supStationInfoPage.getTotal());
        infoData.setPageNo((int) supStationInfoPage.getCurrent());
        infoData.setPageCount((int) supStationInfoPage.getPages());
        logger.info("返回的原始站点数据:{}",JSONObject.toJSONString(infoData));
        return JSONObject.toJSONString(infoData);
    }
}
